package homegroup.inc.servlets;

import homegroup.inc.dao.BookDAO;
import homegroup.inc.dto.Book;
import homegroup.inc.utils.PaginationState;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@WebServlet(name = "books",urlPatterns = {"/lookupbooks/*"})
public class LookupBooks extends HttpServlet {
    @EJB
    BookDAO bookDAO;
    PaginationState paginationState;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("pageNumber");
        HttpSession session = request.getSession();

        Object obj = session.getAttribute("sample");
        boolean bool = false;
        if (obj != null) {
            bool = true;
        }
        if (session.getAttribute("paginator") == null) {
            paginationState = new PaginationState((int)bookDAO.recordsCounter());
        }
        int pageNumber = 1;
        int offset = 0;
        int portionSize = paginationState.getElementsAmountPerPage();
        if (param != null) {
            pageNumber = Integer.parseInt(param);
            offset = pageNumber * portionSize - portionSize;
        }
        paginationState.changeState(pageNumber);

        List<Book> portionOfBooks = bookDAO.getPortionOfBooks(portionSize, offset);
        request.setAttribute("books", portionOfBooks);
        session.setAttribute("paginator", paginationState);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/view/listofbooks.jsp");
        dispatcher.forward(request, response);
    }
}